<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/backHome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card style="margin-top:20px;background:#F1F3F4;">
      <el-row>
        <div style="margin-top: 15px;width:300px;float:left">
          <el-input
            placeholder="请输入内容"
            clearable
            @clear="getUserList"
            v-model="queryInfo.query"
            class="input-with-select"
          >
            <el-button slot="append" @click="getUserList" icon="el-icon-search"></el-button>
          </el-input>
        </div>
        <el-button
          @click="dialogAddVisible = true"
          type="primary"
          style="float:left;margin-left:30px;margin-top: 15px"
        >添加用户</el-button>
      </el-row>
      <!-- 内容区域 -->
      <el-table :data="userInfo" stripe style="width: 100%;margin-top:30px;">
        <el-table-column type="index" label="#" width></el-table-column>
        <el-table-column prop="username" label="姓名" width></el-table-column>
        <el-table-column prop="email" label="邮箱" width></el-table-column>
        <el-table-column prop="mobile" label="电话" width></el-table-column>
        <el-table-column prop="role_name" label="角色" width></el-table-column>
        <el-table-column label="状态" width>
          <template slot-scope="scope">
            <el-switch
              @change="userStateChange(scope.row)"
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width>
          <template slot-scope="scope">
            <el-button
              type="primary"
              @click="editDialog(scope.row)"
              size="mini"
              icon="el-icon-edit"
            ></el-button>
            <el-button @click="delUser(scope.row)" type="danger" size="mini" icon="el-icon-delete"></el-button>
            <el-button
              @click="rolesDialog(scope.row)"
              type="warning"
              size="mini"
              icon="el-icon-s-tools"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[3, 5, 7, 10]"
        :page-size="3"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalNum"
        style="margin-top:20px;"
      ></el-pagination>
    </el-card>

    <!-- 添加用户表单框 -->
    <el-dialog title="收货地址" :visible.sync="dialogAddVisible">
      <el-form :model="addUser" ref="addForm" :rules="addRules">
        <el-form-item label="用户名" prop="username" label-width="100px">
          <el-input v-model="addUser.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" label-width="100px">
          <el-input v-model="addUser.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email" label-width="100px">
          <el-input v-model="addUser.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile" label-width="100px">
          <el-input v-model="addUser.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="toAddReset()">取 消</el-button>
        <el-button type="primary" @click="toAddUser">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 修改用户信息 -->
    <el-dialog title="收货地址" :visible.sync="dialogEditVisible">
      <el-form :model="editInfo" ref="editForm" :rules="editRules">
        <el-form-item label="用户名" label-width="100px">
          <el-input v-model="editInfo.username" disabled autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email" label-width="100px">
          <el-input v-model="editInfo.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile" label-width="100px">
          <el-input v-model="editInfo.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogRolesVisible = false">取 消</el-button>
        <el-button type="primary" @click="editSure('editForm')">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog title="分配角色" :visible.sync="dialogRolesVisible">
          <p style="margin-top:20px;">当前的用户：{{rolesInfo.username}}</p>
          <p style="margin-top:20px;">当前的角色：{{rolesInfo.role_name}}</p>
          <p style="margin-top:20px;">分配新角色：
            <el-select v-model='selectId' placeholder="请选择">
              <el-option v-for="(item,index) in rolesList" :key="index" :value="item.id" :label="item.roleName">
              </el-option>
            </el-select>
          </p>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoles()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  // 组件名称
  name: "demo", // 组件参数 接收来自父组件的数据
  props: [],
  components: {},
  data() {
    // var checkEmail = (rule,val,cb)=>{
    //   const 正则 = ''
    //   if( 正则.text(val) ){
    //     return cd()
    //   }
    //   cd( new Error('请输入合法的。。。') )
    // }
    return {
      searchUser: "",
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 3
      },
      userInfo: [],
      totalNum: 0,
      dialogAddVisible: false,
      addUser: {
        username: "我王家祥想要更多",
        password: "阿西吧",
        email: "666",
        mobile: "66666666666"
      },
      addRules: {
        username: [
          { required: true, message: "用户名不能为空", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" }
        ],
        email: [
          { required: true, message: "邮箱不能为空", trigger: "blur" },
          { min: 3, max: 20, message: "长度在 3 到 20 个字符", trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "手机号不能为空", trigger: "blur" },
          { min: 11, max: 11, message: "长度在11个字符", trigger: "blur" }
        ]
      },
      searchUser: "",
      dialogEditVisible: false,
      editInfo: {},
      editRules: {
        email: [
          { required: true, message: "邮箱不能为空", trigger: "blur" },
          { min: 3, max: 20, message: "长度在 3 到 20 个字符", trigger: "blur" }
          // {validate:名字, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "手机号不能为空", trigger: "blur" },
          { min: 11, max: 11, message: "长度在11个字符", trigger: "blur" }
        ]
      },
      dialogRolesVisible: false,
      rolesInfo: {},
      rolesList: [],
      selectId:''
    };
  },
  computed: {},
  watch: {},
  methods: {
    async getUserList() {
      const { data: res } = await this.$axios.get("users", {
        params: this.queryInfo
      });
      if (res.meta.status !== 200)
        return this.$message.error("获取用户列表失败");
      // this.$message.success("获取用户列表成功");
      this.userInfo = res.data.users;
      this.totalNum = res.data.total;
    },
    async toAddUser() {
      const { data: res } = await this.$axios.post("users", this.addUser);
      console.log(res);
      if (res.meta.status !== 201) return this.$message.error("添加用户失败");
      this.dialogAddVisible = false;
      this.getUserList();
    },
    toAddReset() {
      this.$refs.addForm.resetFields();
      this.dialogAddVisible = false;
    },
    handleSizeChange(val) {
      this.queryInfo.pagesize = val;
      this.getUserList();
    },
    handleCurrentChange(val) {
      this.queryInfo.pagenum = val;
      this.getUserList();
    },
    async delUser(info) {
      const confirmResult = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      console.log(confirmResult);
      if (confirmResult !== "confirm") {
        return this.$message.info("取消删除");
      } else {
        console.log(info.id);
        const { data: res } = await this.$axios.delete("users/" + info.id);
        console.log(res);
        if (res.meta.status !== 200) return this.$message.error("删除失败");
        this.$message.success("删除成功");
        this.getUserList();
      }
    },
    async userStateChange(info) {
      const { data: res } = await this.$axios.put(
        `users/${info.id}/state/${info.mg_state}`
      );
      if (res.meta.status !== 200)
        return this.$message.danger("修改用户状态失败");
      this.$message.success("修改用户状态成功");
    },
    editDialog(info) {
      this.editInfo = info;
      this.dialogEditVisible = true;
    },
    editSure(formName) {
      this.$refs[formName].validate(async valid => {
        if (!valid) return;
        const { data: res } = await this.$axios.put(
          `users/${this.editInfo.id}`,
          this.editInfo
        );
        if (res.meta.status !== 200)
          return this.$message.error("更改用户信息失败");
        this.dialogEditVisible = false;
        this.$message.success("更改用户信息成功");
      });
    },
    async rolesDialog(info) {
      this.rolesInfo = info;
      const { data: res } = await this.$axios.get("roles");
      if (res.meta.status !== 200)
        return this.$message.error("获取角色列表失败");
      this.rolesList = res.data;
      console.log(this.rolesList)
      this.dialogRolesVisible = true;
    },
    async editRoles(){
      // console.log(this.rolesInfo.id)
      const {data:res} = await this.$axios.put(`users/${this.rolesInfo.id}/role`,{rid:this.selectId})
      if( res.meta.status !== 200 ) return this.$message.error('修改角色失败')
      this.getUserList()
      this.$message.success('修改角色成功')
      console.log(res)
      this.dialogRolesVisible = false
    }
  },
  beforeCreate() {},
  created() {},
  beforeMount() {},
  mounted() {
    this.getUserList();
  }
};
</script> 
<style scoped>
</style>
